﻿using System;
using System.Text;

namespace Com.Lancetinc.Evs.Communications
{
    /// <summary>
    /// 控制字符
    /// </summary>
    public enum CtrlChars
    {
        BEGIN = '<',
        END = '>',
    }

    /// <summary>
    /// 数据包
    /// </summary>
    public class Packet
    {
        /// <summary>
        /// 创建时间
        /// </summary>
        public readonly DateTime CreateTime = DateTime.Now;

        /// <summary>
        /// 数据包类型
        /// </summary>
        public readonly CtrlCmds Command;

        /// <summary>
        /// 数据
        /// </summary>
        public readonly string Data;

        /// <summary>
        /// 原始二进制文件(不包含!< >)
        /// </summary>
        public byte[] OrgBytes { get; set; }

        public Packet(CtrlCmds command, string data)
        {
            this.Command = command;
            this.Data = data;
        }

        public Packet(CtrlCmds command)
        {
            this.Command = command;
        }


        /// <summary>
        /// 创建用于传输的字节数据。
        /// </summary>
        /// <returns></returns>
        public byte[] Serialize()
        {
            var sendString = $"!{(char)CtrlChars.BEGIN}{(char)this.Command}{Data ?? string.Empty}{(char)CtrlChars.END}";
            return Encoding.ASCII.GetBytes(sendString);
        }

        public override string ToString()
        {
            return $"{Command}:{Data}";
        }
    }
}
